<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>俄罗斯方块</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <style>
        * {
            box-sizing: border-box;
            touch-action: none;
            margin: 0;
            padding: 0;
        }
        html, body {
            height: 100%;
            overflow: hidden;
        }
        body {
            display: flex;
            flex-direction: column;
            background: #f0f0f0;
            font-family: Arial, sans-serif;
        }
        #score {
            font-size: 24px; 
            padding: 15px;
            color: #333;
            text-align: center;
            flex-shrink: 0;
        }
        #game-wrapper {
            flex: 1;
            width: 100%;
            max-width: 400px;
            margin: 0 auto;
            padding: 10px;
            position: relative;
        }
        canvas {
            width: 100%;
            height: 100%;
            border: 2px solid #333;
            background: #fff;
        }
        #controls {
            position: fixed;
            bottom: 20px;
            left: 0;
            right: 0;
            display: flex;
            justify-content: center;
            gap: 15px;
            padding: 0 10px;
            z-index: 10;
        }
        .control-btn {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: #4CAF50;
            color: white;
            border: none;
            font-size: 24px;
            cursor: pointer;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            transition: all 0.1s;
            touch-action: manipulation;
        }
        .control-btn:active {
            transform: scale(0.95);
            background: #45a049;
        }
        #rotate-btn {
            background: #2196F3;
        }
        #game-over {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 30px 40px;
            border-radius: 15px;
            box-shadow: 0 0 25px rgba(0,0,0,0.2);
            text-align: center;
            z-index: 100;
        }
        #restart-btn {
            background: #4CAF50;
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 15px;
            transition: all 0.3s;
        }
        #restart-btn:hover {
            background: #45a049;
        }
        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 99;
            display: none;
        }
        @media (max-width: 768px) {
            #controls {
                display: flex;
            }
        }
    </style>
</head>
<body>
    <div id="score">得分: 0</div>
    <div id="game-wrapper">
        <canvas id="game"></canvas>
    </div>
    
    <div id="controls">
        <button class="control-btn" id="left-btn">←</button>
        <button class="control-btn" id="down-btn">↓</button>
        <button class="control-btn" id="right-btn">→</button>
        <button class="control-btn" id="rotate-btn">↻</button>
    </div>

    <div id="game-over">
        <h2>游戏结束！</h2>
        <p>最终得分: <span id="final-score">0</span></p>
        <button id="restart-btn">重新开始</button>
    </div>
    <div id="overlay" class="overlay"></div>

<script>
// 游戏常量
const SHAPES = [
    [[1,1,1,1]], // I
    [[1,1,1],[0,1,0]], // T
    [[1,1,1],[1,0,0]], // L
    [[1,1,1],[0,0,1]], // J
    [[1,1],[1,1]], // O
    [[1,1,0],[0,1,1]], // S
    [[0,1,1],[1,1,0]]  // Z
];
const COLORS = [
    '#00f0f0', '#f0a000', '#f0f000', '#a000f0', 
    '#f00000', '#00f000', '#0000f0'
];
const COLS = 10;
const ROWS = 20;

// 游戏变量
let canvas, ctx;
let BLOCK_SIZE;
let board = [];
let currentPiece = null;
let score = 0;
let gameInterval;
let gameOver = false;

// DOM元素
const gameOverModal = document.getElementById('game-over');
const overlay = document.getElementById('overlay');
const restartBtn = document.getElementById('restart-btn');
const finalScore = document.getElementById('final-score');

function initCanvas() {
    canvas = document.getElementById('game');
    ctx = canvas.getContext('2d');
    
    const wrapper = document.getElementById('game-wrapper');
    const scoreHeight = document.getElementById('score').offsetHeight;
    const controlsHeight = document.getElementById('controls').offsetHeight;
    
    // 计算可用高度
    const maxHeight = window.innerHeight - scoreHeight - controlsHeight - 30;
    const cellSize = Math.min(
        wrapper.offsetWidth / COLS,
        maxHeight / ROWS
    );
    
    BLOCK_SIZE = Math.floor(cellSize);
    canvas.width = COLS * BLOCK_SIZE;
    canvas.height = ROWS * BLOCK_SIZE;
}

function createPiece() {
    const type = Math.floor(Math.random() * SHAPES.length);
    return {
        shape: SHAPES[type],
        color: COLORS[type],
        x: Math.floor(COLS/2) - Math.floor(SHAPES[type][0].length/2),
        y: 0
    };
}

function drawBlock(x, y, color) {
    ctx.fillStyle = color;
    ctx.fillRect(x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE-1, BLOCK_SIZE-1);
    ctx.strokeStyle = 'rgba(0,0,0,0.1)';
    ctx.strokeRect(x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
}

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 绘制棋盘
    for (let y = 0; y < ROWS; y++) {
        for (let x = 0; x < COLS; x++) {
            if (board[y][x]) {
                drawBlock(x, y, board[y][x]);
            }
        }
    }
    
    // 绘制当前方块
    if (currentPiece) {
        currentPiece.shape.forEach((row, dy) => {
            row.forEach((value, dx) => {
                if (value) {
                    drawBlock(currentPiece.x + dx, currentPiece.y + dy, currentPiece.color);
                }
            });
        });
    }
}

function collision() {
    return currentPiece.shape.some((row, dy) => 
        row.some((value, dx) => {
            if (!value) return false;
            const newX = currentPiece.x + dx;
            const newY = currentPiece.y + dy;
            return (
                newX < 0 ||
                newX >= COLS ||
                newY >= ROWS ||
                (board[newY] && board[newY][newX])
            );
        })
    );
}

function merge() {
    currentPiece.shape.forEach((row, dy) => {
        row.forEach((value, dx) => {
            if (value && currentPiece.y + dy < ROWS) {
                board[currentPiece.y + dy][currentPiece.x + dx] = currentPiece.color;
            }
        });
    });
}

function rotate() {
    if (!currentPiece) return;
    
    const shape = currentPiece.shape;
    const newShape = shape[0].map((_, i) => 
        shape.map(row => row[i]).reverse()
    );
    const oldShape = currentPiece.shape;
    currentPiece.shape = newShape;
    if (collision()) {
        currentPiece.shape = oldShape;
    }
    draw();
}

function clearLines() {
    let linesCleared = 0;
    for (let y = ROWS - 1; y >= 0; y--) {
        if (board[y].every(cell => cell)) {
            board.splice(y, 1);
            board.unshift(Array(COLS).fill(0));
            linesCleared++;
            y++;
        }
    }
    if (linesCleared) {
        score += linesCleared * 100;
        document.getElementById('score').textContent = `得分: ${score}`;
    }
}

function moveDown() {
    if (!currentPiece || gameOver) return;
    
    currentPiece.y++;
    if (collision()) {
        currentPiece.y--;
        merge();
        clearLines();
        currentPiece = null;
    }
    draw();
}

function update() {
    if (gameOver) return;
    
    if (!currentPiece) {
        currentPiece = createPiece();
        if (collision()) {
            gameOver = true;
            showGameOver();
            return;
        }
    }
    
    currentPiece.y++;
    if (collision()) {
        currentPiece.y--;
        merge();
        clearLines();
        currentPiece = null;
    }
    
    draw();
}

function resetGame() {
    board = Array.from({length: ROWS}, () => Array(COLS).fill(0));
    score = 0;
    gameOver = false;
    currentPiece = null;
    document.getElementById('score').textContent = `得分: 0`;
    gameOverModal.style.display = 'none';
    overlay.style.display = 'none';
    
    clearInterval(gameInterval);
    gameInterval = setInterval(update, 1000);
    draw();
}

function showGameOver() {
    finalScore.textContent = score;
    gameOverModal.style.display = 'block';
    overlay.style.display = 'block';
    clearInterval(gameInterval);
}

function setupControls() {
    const controlsMap = {
        'left-btn': () => {
            if (!currentPiece) return;
            currentPiece.x--;
            if (collision()) currentPiece.x++;
            draw();
        },
        'right-btn': () => {
            if (!currentPiece) return;
            currentPiece.x++;
            if (collision()) currentPiece.x--;
            draw();
        },
        'down-btn': moveDown,
        'rotate-btn': () => {
            if (currentPiece) {
                rotate();
                draw();
            }
        }
    };

    Object.entries(controlsMap).forEach(([id, action]) => {
        const btn = document.getElementById(id);
        const handler = (e) => {
            e.preventDefault();
            if (gameOver) return;
            action();
        };
        btn.addEventListener('touchstart', handler);
        btn.addEventListener('mousedown', handler);
    });

    // 键盘控制
    document.addEventListener('keydown', (e) => {
        if (gameOver) return;
        
        switch(e.keyCode) {
            case 37: // Left
                controlsMap['left-btn']();
                break;
            case 39: // Right
                controlsMap['right-btn']();
                break;
            case 40: // Down
                moveDown();
                break;
            case 38: // Up
                controlsMap['rotate-btn']();
                break;
            case 82: // R
                resetGame();
                break;
        }
    });

    // 重新开始按钮
    restartBtn.addEventListener('click', resetGame);
}

function handleResize() {
    initCanvas();
    draw();
}

function initGame() {
    initCanvas();
    setupControls();
    resetGame();
    window.addEventListener('resize', handleResize);
    window.addEventListener('orientationchange', handleResize);
}

// 启动游戏
initGame();
</script>
</body>
</html>